package dao;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class CodeValidateDao {
    public static final Logger logger = LogManager.getLogger(CodeValidateDao.class);
    char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Random random = new Random();
        StringBuilder stringBuffer = new StringBuilder();
        //验证码宽度
        int width = 900;
        //验证码高度
        int height = 240;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.black);
        graphics.drawRect(0, 0, width, height);
        graphics.setColor(Color.white);
        graphics.fillRect(1, 1, width - 2, height - 2);
        graphics.setColor(Color.blue);

        //混淆线个数
        int lineCount = 123;
        for (int i = 0; i < lineCount; i++) {
            graphics.drawLine(random.nextInt(width), random.nextInt(width), random.nextInt(width), random.nextInt(width));
        }

        graphics.setColor(Color.blue);
        graphics.setFont(new Font("宋体", Font.PLAIN, 170));

        //验证码个数
        int codeCount = 4;
        for (int i = 0; i < codeCount; i++) {
            char c = codeSequence[random.nextInt(codeSequence.length)];
            stringBuffer.append(c);
            graphics.drawString(c + "", 150 * (i + 1), 175);
        }

        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(bufferedImage, "png", outputStream);

        HttpSession session = request.getSession();
        session.setAttribute("codeValidate", stringBuffer.toString());

        logger.info("codeValidate:Code is " + stringBuffer);

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");
        outputStream.close();
    }
}
